package com.cdks.wuxiu.api.service.mongo;

import com.cdks.wuxiu.entity.mongodb.QuizAnswerInfo;
import com.cdks.wuxiu.entity.mongodb.QuizResultInfo;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


/**
 * 心理测试答案 服务实现类
 */
@Slf4j
@Service
public class QuizAnswerInfoServiceImpl implements QuizAnswerInfoService {
    @Resource
    private MongoTemplate mongoTemplate;


    @Override
    public QuizAnswerInfo getAnswer(Long topicId, int score) {
        Query query = Query.query(Criteria.where("topicId").is(topicId));

        return mongoTemplate.findOne(query, QuizAnswerInfo.class);
    }

    @Override
    public QuizResultInfo getResultrByScore(Long topicId, int score) {
        Aggregation aggregation = Aggregation.newAggregation(
            //先筛选
            Aggregation.match(Criteria.where("topicId").is(topicId)),            
            //解构
            Aggregation.unwind("$answer"),
            //再次筛选
            Aggregation.match(Criteria.where("answer.score.min").lte(score).and("answer.score.max").gte(score)),
            //排除字段
            Aggregation.project().andExclude("answer.score")
        );

        //查询
        AggregationResults<QuizResultInfo> aggregate = mongoTemplate.aggregate(aggregation, QuizResultInfo.class, QuizResultInfo.class);
        QuizResultInfo result = aggregate.getUniqueMappedResult();//获取数据

        return result;
    }
}
